import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import Axios from "axios";
//请求数据
function async_request_action() {
    return dispatch => {
        Axios.get("/list").then(res => {
            dispatch(getdata_action(res.data.list));
        });
    };
}
//获取数据action
function getdata_action(data) {
    return {
        type: "GETDATA_ACTION",
        data
    };
}
//添加购物车action
function add_cart_action(item) {
    return {
        type: "ADD_CART_ACTION",
        item
    };
}
//删除商品action
function delete_cart_action(id) {
    return {
        type: "DELETE_CART_ACTION",
        id
    };
}
//新增收货地址action
function add_address_action(address) {
    return {
        type: "ADD_ADDRESS_ACTION",
        address
    };
}

let obj = {
    allList: [],
    cartList: [],
    addressList: [],
    id: 1
};

function reducer(state = obj, action) {
    //深拷贝state
    state = JSON.parse(JSON.stringify(state));

    switch (action.type) {
        case "GETDATA_ACTION":
            state.allList = action.data;
            return state;

        case "ADD_CART_ACTION":
            let find = state.cartList.find((item, index) => {
                return item.id === action.item.id;
            });
            if (find) {
                find.count++;
            } else {
                action.item.count = 1;
                state.cartList.push(action.item);
            }
            return state;

        case "DELETE_CART_ACTION":
            let ind = state.cartList.findIndex((item, index) => {
                return item.id === action.id;
            });
            if (ind !== -1) {
                state.cartList.splice(ind, 1);
            }
            return state;

        case "ADD_ADDRESS_ACTION":
            action.address.id = state.id;
            state.addressList.push(action.address);
            state.id++;
            return state;

        default:
            return state;
    }
}

let store = createStore(reducer, applyMiddleware(thunk));

export {
    store,
    async_request_action,
    add_cart_action,
    delete_cart_action,
    add_address_action
};
